package com.ruoyi.docs.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ruoyi.common.annotation.CommunityScope;
import com.ruoyi.common.core.domain.BizTree;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.docs.domain.BizColumn;
import com.ruoyi.docs.domain.BizTreeColumn;
import com.ruoyi.docs.domain.dto.ArticleTreeDto;
import com.ruoyi.docs.domain.dto.MpArticleCommand;
import com.ruoyi.docs.domain.dto.MpArticleResource;
import com.ruoyi.docs.service.IBizColumnService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.docs.mapper.BizArticleMapper;
import com.ruoyi.docs.domain.BizArticle;
import com.ruoyi.docs.service.IBizArticleService;

/**
 * 栏目信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-05-05
 */
@Service
public class BizArticleServiceImpl implements IBizArticleService 
{
    @Autowired
    private BizArticleMapper bizArticleMapper;
    @Autowired
    private IBizColumnService bizColumnService;
    /**
     * 查询栏目信息
     * 
     * @param articleId 栏目信息主键
     * @return 栏目信息
     */
    @Override
    public BizArticle selectBizArticleByArticleId(Long articleId)
    {
        return bizArticleMapper.selectBizArticleByArticleId(articleId);
    }

    /**
     * 查询栏目信息列表
     * 
     * @param bizArticle 栏目信息
     * @return 栏目信息
     */
    @Override
    @CommunityScope
    public List<BizArticle> selectBizArticleList(BizArticle bizArticle)
    {
        return bizArticleMapper.selectBizArticleList(bizArticle);
    }

    /**
     * 新增栏目信息
     * 
     * @param bizArticle 栏目信息
     * @return 结果
     */
    @Override
    public int insertBizArticle(BizArticle bizArticle)
    {
        bizArticle.setCreateTime(DateUtils.getNowDate());
        return bizArticleMapper.insertBizArticle(bizArticle);
    }

    /**
     * 修改栏目信息
     * 
     * @param bizArticle 栏目信息
     * @return 结果
     */
    @Override
    public int updateBizArticle(BizArticle bizArticle)
    {
        bizArticle.setUpdateTime(DateUtils.getNowDate());
        return bizArticleMapper.updateBizArticle(bizArticle);
    }

    /**
     * 批量删除栏目信息
     * 
     * @param articleIds 需要删除的栏目信息主键
     * @return 结果
     */
    @Override
    public int deleteBizArticleByArticleIds(Long[] articleIds)
    {
        return bizArticleMapper.deleteBizArticleByArticleIds(articleIds);
    }

    /**
     * 删除栏目信息信息
     * 
     * @param articleId 栏目信息主键
     * @return 结果
     */
    @Override
    public int deleteBizArticleByArticleId(Long articleId)
    {
        return bizArticleMapper.deleteBizArticleByArticleId(articleId);
    }

    /**
     * 类目->子类目->文章信息
     *
     * @return
     */
    @Override
    public List<BizTree> getTree(ArticleTreeDto articleTreeDto) {
        BizColumn column = new BizColumn();
        column.setColumnType(0L);
        column.setStatus("0");
        List<BizColumn> bizColumns = bizColumnService.selectBizColumnList(column);


        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysRole sysRole = loginUser.getUser().getRoles().get(0);

        if (sysRole.getRoleKey().equals("committee") || sysRole.getRoleKey().equals("business")
                || sysRole.getRoleKey().equals("common")) {
            List<BizColumn> newDepts = new ArrayList<>();
            List<Long> list = Arrays.asList(1l, 11l, 3l, 2l);
            for (BizColumn dept : bizColumns) {
                if (list.contains(dept.getColumnId())) {
                    continue;
                }
                newDepts.add(dept);
            }
            bizColumns = newDepts;
        }

        List<BizTree> trees = new ArrayList();
        for (BizColumn bizColumn : bizColumns) {
            if (bizColumn.getParentId().equals(0L)) {
                BizTree bizTree = new BizTree();
                bizTree.setValue(bizColumn.getColumnId().toString());
                bizTree.setLabel(bizColumn.getColumnName());
                trees.add(bizTree);
            }

        }
        for (BizTree tree : trees) {
            List<BizTree.FirstChildren> childrens = new ArrayList<>();
            for (BizColumn bizColumn : bizColumns) {
                if (tree.getValue().equals(bizColumn.getParentId().toString())) {
                    BizTree.FirstChildren children = new BizTree.FirstChildren();
                    children.setValue(bizColumn.getColumnId().toString());
                    children.setLabel(bizColumn.getColumnName());
                    childrens.add(children);
                }
            }
            tree.setChildren(childrens);
        }
        //当前分类下的文章
        for (BizTree tree : trees) {
            if (StringUtils.isNotEmpty(tree.getChildren())){
                for (BizTree.FirstChildren child : tree.getChildren()) {
                    BizArticle bizArticle = new BizArticle();
                    bizArticle.setColumnId(Long.parseLong(child.getValue()));
                    //bizArticle.setIsCarousel(1);//显示轮播
                    bizArticle.setStatus("0");//显示正常
                    if (articleTreeDto != null && articleTreeDto.getCommunityId() != null) {
                        bizArticle.setCommunityId(articleTreeDto.getCommunityId());
                    }
                    List<BizArticle> articles = this.selectBizArticleList(bizArticle);
                    List<BizTree.FirstChildren> articleTree = new ArrayList<>();
                    for (BizArticle article : articles) {
                        BizTree.FirstChildren bizTree = new BizTree.FirstChildren();
                        bizTree.setValue(article.getArticleId().toString());
                        bizTree.setLabel(article.getTitle());
                        articleTree.add(bizTree);
                    }
                    child.setChildren(articleTree);
                }
            }
            else {
                BizArticle bizArticle = new BizArticle();
                bizArticle.setColumnId(Long.parseLong(tree.getValue()));
                // bizArticle.setIsCarousel(1);//显示轮播
                bizArticle.setStatus("0");//显示正常
                if (articleTreeDto != null && articleTreeDto.getCommunityId() != null) {
                    bizArticle.setCommunityId(articleTreeDto.getCommunityId());
                }
                List<BizArticle> bizArticles = this.selectBizArticleList(bizArticle);
                List<BizTree.FirstChildren> articleTree = new ArrayList<>();
                for (BizArticle article : bizArticles) {
                    BizTree.FirstChildren bizTree = new BizTree.FirstChildren();
                    bizTree.setValue(article.getArticleId().toString());
                    bizTree.setLabel(article.getTitle());
                    articleTree.add(bizTree);
                }
                tree.setChildren(articleTree);
            }
        }
        return trees;
    }

    @Override
    public MpArticleResource getMpArticle(MpArticleCommand mpArticle) {
        MpArticleResource res = new MpArticleResource();
        this.checkUrl(mpArticle.getUrl());
        try {
            Document doc = Jsoup.connect(mpArticle.getUrl()).get();
            String jsContent = doc.getElementById("js_content").html();
            String title = doc.getElementById("activity-name").html();
            Elements elements = doc.getElementsByTag("meta");
            Element first = elements.select("meta[property=og:image]").first();
            String imgurl = first.attr("content");
            String jsName = doc.getElementById("js_name").text();
            //内容
            String outContent = jsContent.replace("data-src", "src");
            res.setTitle(title);
            res.setContent(outContent);
            res.setImgUrl(imgurl);
            res.setSource(jsName);

        }
        catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }

        return res;
    }
    /**
     * 检测文章链接是否合法
     */
    public static String checkUrl(String url) {

        String WX_DOMAIN = "https://mp.weixin.qq.com";
        if (url == null) {
            throw new ServiceException("请输入文章链接");
        }
        if (!url.startsWith(WX_DOMAIN)) {
            throw new ServiceException("请输入微信公众号文章链接");
        }
        return null;
    }
}
